using System;
using System.Collections.Generic;
using System.Text;
using EnvDTE;
using Microsoft.Practices.RecipeFramework;
using VSSDKAssist.Assets.Helpers;
using EnvDTE80;
using VSSDKAssist.Recipes.Common.Actions;
using Microsoft.VisualStudio.TextTemplating.VSHost;
using System.IO;
using VSLangProj;
using VSSDKAssist.Assets.Actions.Base;
using System.Globalization;

namespace VSSDKAssist.Recipes.TransformTemplates
{
	/// <summary>
	/// Action that transforms the text templates files for a project or a folder
	/// </summary>
	public class TransformTemplatesAction : ActionBase
	{
		#region Constants
		private const string CustomToolName = "TextTemplatingFileGenerator";
		#endregion

		#region Properties
		private string extension;

		/// <summary>
		/// Gets or sets the extension.
		/// </summary>
		/// <value>The extension.</value>
		[Input(Required = true)]
		public string Extension
		{
			get { return extension; }
			set { extension = value; }
		}

		private Project project;

		/// <summary>
		/// Gets or sets the project.
		/// </summary>
		/// <value>The project.</value>
		[Input(Required = false)]
		public Project Project
		{
			get { return project; }
			set { project = value; }
		}

		private ProjectItem projectItem;

		/// <summary>
		/// Gets or sets the project item.
		/// </summary>
		/// <value>The project item.</value>
		[Input(Required = false)]
		public ProjectItem ProjectItem
		{
			get { return projectItem; }
			set { projectItem = value; }
		}
		#endregion

		/// <summary>
		/// Called when [execute].
		/// </summary>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		protected override void OnExecute()
		{
			StatusBarHelper statusBarHelper = new StatusBarHelper(this.Site as IServiceProvider);
			OutputWindowHelper outputWindowHelper =
				new OutputWindowHelper((DTE2)VisualStudio, Properties.Resources.VSSDKAssistPane);
			ProjectItemIterator iterator;

			if(this.project != null)
			{
				iterator = new ProjectItemIterator(this.Project);
			}
			else
			{
				iterator = new ProjectItemIterator(this.ProjectItem);
			}

			string message = string.Empty;
			bool tryToGenerate = true;
			string name = string.Empty;

			foreach(ProjectItem item in iterator)
			{
				try
				{
					if(item.Properties.Item("Extension").Value.ToString().Equals(
						this.Extension, StringComparison.OrdinalIgnoreCase))
					{
						if(item.Properties.Item("CustomTool").Value.ToString().Equals(
							CustomToolName, StringComparison.OrdinalIgnoreCase))
						{
							if(item.ProjectItems != null && item.ProjectItems.Count > 0)
							{
								foreach(ProjectItem dependentItem in item.ProjectItems)
								{
									try
									{
										name = dependentItem.Properties.Item("FullPath").Value.ToString();
									}
									catch(ArgumentException)
									{
										tryToGenerate = false;
									}

									if(!string.IsNullOrEmpty(name))
									{
										if(!VisualStudio.SourceControl.IsItemUnderSCC(name))
										{
											if(File.Exists(name))
											{
												FileAttributes attributes = File.GetAttributes(name);
												if((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
												{
													tryToGenerate = false;
													
													message = string.Format(
																Properties.Resources.TransformTemplateReadOnly,
																string.Format(
																	CultureInfo.CurrentCulture,
																	"{0}{1}",
																	Path.GetFileNameWithoutExtension(item.Name),
																	this.extension));

													LogMessage(outputWindowHelper, statusBarHelper, message);
												}
											}
										}
									}
								}
							}

							if(tryToGenerate)
							{
								try
								{
									message =
										string.Format(
											CultureInfo.CurrentCulture,
											Properties.Resources.TransformTemplateMessage,
											item.Name,
											CustomToolName);

									LogMessage(outputWindowHelper, statusBarHelper, message);

									((VSProjectItem)item.Object).RunCustomTool();
								}
								catch
								{
									message = string.Format(
												CultureInfo.CurrentCulture,
												Properties.Resources.TransformTemplateMessageError,
												item.Name);

									LogMessage(outputWindowHelper, statusBarHelper, message);
								}		
							}
						}
					}
				}
				catch(ArgumentException)
				{
					//Do nothing, goto the next ProjectItem
				}
			}
		}

		/// <summary>
		/// Called when [undo].
		/// </summary>
		protected override void OnUndo()
		{
		}

		#region Private Implementation
		private static void LogMessage(OutputWindowHelper outputWindowHelper, StatusBarHelper statusBarHelper, string message)
		{
			outputWindowHelper.WriteMessage(message);
			statusBarHelper.DisplayMessage(message);
		}
		#endregion
	}
}